﻿using System;
using System.Diagnostics;
using System.Net.Http;
using System.Threading.Tasks;

namespace CSharpX.WeiXin
{
    /// <summary>
    /// 微信API
    /// </summary>
    public class WeiXinApi
    {/// <summary>
     /// 通过临时票据code获取接口调用凭证access_token
     /// </summary>
     /// <param name="appId"></param>
     /// <param name="appSecret"></param>
     /// <param name="code">临时票据</param>
     /// <returns></returns>
        public static async Task<AccessToken> GetAccessToken(string appId, string appSecret, string code)
        {
            try
            {
                using (HttpClient httpClient = new HttpClient())
                {
                    string text = await httpClient.GetStringAsync(@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appId + "&secret=" + appSecret + "&code=" + code + "&grant_type=authorization_code");
                    if (text == null || text.Length == 0)
                    {
                        //Log.Error("GetUserinfo出错,GetStringAsync结果为null");
                        return null;
                    }
                    AccessToken accessToken = Newtonsoft.Json.JsonConvert.DeserializeObject<AccessToken>(text);
                    return accessToken;
                }
            }
            catch// (Exception e)
            {
                //Log.Error("WeiXin.GetAccessToken出错:" + e);
            }
            return null;
        }
        /// <summary>
        /// 通过接口调用凭证access_token获取userinfo
        /// </summary>
        /// <param name="access_token">接口调用凭证</param>
        /// <param name="openid"></param>
        /// <returns></returns>
        public static async Task<Userinfo> GetUserinfo(string access_token, string openid)
        {
            try
            {
                using (HttpClient httpClient = new HttpClient())
                {
                    string text = await httpClient.GetStringAsync(@"https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid);
                    if (text == null || text.Length == 0)
                    {
                        //Log.Error("GetUserinfo出错,GetStringAsync结果为null");
                        return null;
                    }
                    Userinfo userinfo = Newtonsoft.Json.JsonConvert.DeserializeObject<Userinfo>(text);
                    return userinfo;
                }
            }
            catch (Exception e)
            {
                Log.Error("WeiXin.GetUserinfo出错:" + e);
            }
            return null;
        }
        /// <summary>
        /// GetHeadimg
        /// </summary>
        /// <param name="headimgurl"></param>
        /// <returns></returns>
        public static async Task<byte[]> GetHeadimg(string headimgurl)
        {
            try
            {
                using (HttpClient httpClient = new HttpClient())
                {
                    byte[] bytes = await httpClient.GetByteArrayAsync(headimgurl);
                    if (bytes == null || bytes.Length == 0)
                    {
                        //Log.Error("GetHeadimg出错,GetByteArrayAsync结果为null");
                        return null;
                    }
                    return bytes;
                }
            }
            catch// (Exception e)
            {
                //Log.Error("WeiXin.GetHeadimg出错:" + e);
            }
            return null;
        }

        /// <summary>
        /// 获取扫码登录的二维码
        /// </summary>
        /// <param name="appID"></param>
        /// <param name="redirectUri"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        public static async Task<QrcodeData> GetLoginQrcode(string appID, string redirectUri, string state)
        {
            try
            {
                string qrcodeName;
                string uuid;

                //获取二维码页面
                using (HttpClient httpClient = new HttpClient())
                {
                    string text = await httpClient.GetStringAsync($"https://open.weixin.qq.com/connect/qrconnect?appid={appID}&redirect_uri={redirectUri}&response_type=code&scope=snsapi_login&state={state}#wechat_redirect");
                    if (text == null || text.Length == 0)
                    {
                        //Log.Error("GetLoginQrcode出错,GetStringAsync结果为null");
                        return null;
                    }

                    //获取二维码图片名字
                    string qs = "/connect/qrcode/";
                    int qrcodeIndex = text.IndexOf(qs);
                    if (qrcodeIndex > 0)
                    {
                        qrcodeName = text.Substring(qrcodeIndex + qs.Length, 16);
                    }
                    else
                    {
                        //Log.Error("GetLoginQrcode出错,获取二维码图片id结果为null");
                        return null;
                    }

                    //获取uuid
                    string us = ".com/connect/l/qrconnect?uuid=";
                    int uuidIndex = text.IndexOf(us);
                    if (uuidIndex > 0)
                    {
                        uuid = text.Substring(uuidIndex + us.Length, 16);
                    }
                    else
                    {
                        //Log.Error("GetLoginQrcode出错,获取uuid结果为null");
                        return null;
                    }
                }

                using (HttpClient httpClient = new HttpClient())
                {
                    byte[] bytes = await httpClient.GetByteArrayAsync($"https://open.weixin.qq.com/connect/qrcode/{qrcodeName}");
                    if (bytes == null || bytes.Length == 0)
                    {
                        //Log.Error("GetHeadimg出错,GetByteArrayAsync结果为null");
                        return null;
                    }
                    QrcodeData qrcodeData = new QrcodeData();
                    qrcodeData.img = bytes;
                    qrcodeData.uuid = uuid;
                    return qrcodeData;
                }
            }
            catch// (Exception e)
            {
                //Log.Error("WeiXin.GetLoginQrcode出错:" + e);
            }
            return null;
        }
        /// <summary>
        /// 获取扫码登录的二维码的状态
        /// </summary>
        /// <param name="uuid"></param>
        /// <returns></returns>
        public static async Task<QrcodeStatusData> GetLoginQrcodeStatus(string uuid)
        {
            try
            {
                long t = DateTime.Now.Ticks / 10000 - 62135596800000;
                using (HttpClient httpClient = new HttpClient())
                {
                    string text = await httpClient.GetStringAsync($"https://lp.open.weixin.qq.com/connect/l/qrconnect?uuid={uuid}&_={t}");
                    if (text == null || text.Length == 0)
                    {
                        //Log.Error("GetLoginQrcodeStatus出错,GetStringAsync结果为null");
                        return null;
                    }
                    QrcodeStatusData qrcodeStatusData = new QrcodeStatusData();
                    string[] ss = text.Split(new char[] { '=', ';', '\'' }, StringSplitOptions.RemoveEmptyEntries);
                    switch (ss[1])
                    {
                        case "408"://初始状态，无操作
                            qrcodeStatusData.status = QrcodeStatus.已经准备;
                            break;
                        case "404"://已经扫描
                            qrcodeStatusData.status = QrcodeStatus.已经扫描;
                            break;
                        case "405"://扫描并登录
                            qrcodeStatusData.code = ss[3];
                            qrcodeStatusData.status = QrcodeStatus.扫描并登录;
                            break;
                        case "403"://扫描后取消
                            qrcodeStatusData.status = QrcodeStatus.扫描后取消;
                            break;
                        case "402"://二维码过期
                            qrcodeStatusData.status = QrcodeStatus.二维码过期;
                            break;
                        case "606"://调用太频繁
                            qrcodeStatusData.status = QrcodeStatus.调用太频繁;
                            break;
                        default:
                            qrcodeStatusData.status = QrcodeStatus.未知;
                            break;
                    }
                    return qrcodeStatusData;
                }
            }
            catch// (Exception e)
            {
                //Log.Error("WeiXin.GetUserinfo出错:" + e);
            }
            return null;
        }
    }
}
